package com.zjt.smart.mvp.presenter.base;

import android.text.TextUtils;

import com.zjt.smart.api.server.BaseServer;
import com.zjt.smart.mvp.view.LoadView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class NoDataCallback extends BaseCallback{
    private static final String TAG = "NoDataCallback";
    protected LoadView mLoadView;

    public NoDataCallback(LoadView loadView) {
        mLoadView = loadView;
    }

    @Override
    public void onLoadCache(long cacheTime, String cachStr) {

    }

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (call == null || call.isCanceled()){
            return;
        }
        if (!response.isSuccess()){
            mLoadView.onFail(response.code(), "At " + TAG + "#onResponse-> " + response.errorBody().toString());
            return;
        }
        List<Object> data = new ArrayList<>();
        String string = null;
        try {
            string = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(string)){
            mLoadView.onSuccess(null);
        }else {
            data.add(new String(string));
            mLoadView.onSuccess(data);
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        if (call == null || call.isCanceled()){
            return;
        }
        mLoadView.onFail(BaseServer.SYNTAX, "At " + TAG + "#onFailure-> " + t.toString());
    }
}
